import 'dart:io';

// import 'package:cherrilog/cherrilog.dart';
import 'package:file_picker/file_picker.dart';
import 'package:get/get.dart';
import 'package:path_provider/path_provider.dart';

import '../../../base/BaseController.dart';
import 'package:image/image.dart' as img;
import 'package:path/path.dart' as path;

import '../../../src/rust/api/image_handler.dart';

class PictureAshingController extends BaseController {
  final imagePath = ''.obs;
  final outputPath = ''.obs;
  final rustImagePath = ''.obs;
  final rustOutputPath = ''.obs;
  final time1 = 0.obs;
  final time2 = 0.obs;

  choosePicture({int type = 0}) async {
    final result = await FilePicker.platform.pickFiles();
    if (result != null) {
      final path = result.files.single.path;
      if (type == 0) {
        imagePath.value = path!;
      } else {
        rustImagePath.value = path!;
      }
    }
  }

  ashingFromDart() async {
    int startTime = DateTime.now().millisecondsSinceEpoch;
    File file = File(imagePath.value);
    img.Image image = img.decodeImage(file.readAsBytesSync())!;
    img.Image grayImage =
        img.Image(width: image.width, height: image.height, numChannels: 1);
    for (int i = 0; i < image.height; i++) {
      for (int j = 0; j < image.width; j++) {
        img.Pixel pixel = image.getPixel(j, i);
        num r = pixel.r;
        num g = pixel.g;
        num b = pixel.b;
        int luma = (0.299 * r + 0.587 * g + 0.114 * b).round();
        grayImage.setPixel(j, i, img.ColorInt8.rgba(luma, luma, luma, 1));
      }
    }
    final directory = await getApplicationDocumentsDirectory();
    final fileName = path.basename(imagePath.value);
    // info('fileName: $fileName');
    Directory tempDirectory = Directory(directory.path + '\\output');
    if (!tempDirectory.existsSync()) {
      tempDirectory.createSync();
    }

    final newName = path.join(tempDirectory.path, fileName);
    final outputFile = File(newName);
    await outputFile.writeAsBytes(img.encodePng(grayImage));
    outputPath.value = newName;
    int endTime = DateTime.now().millisecondsSinceEpoch;
    time1.value = endTime - startTime;
  }

  ashingFromRust() async {
    int startTime = DateTime.now().millisecondsSinceEpoch;
    String src = rustImagePath.value;
    final directory = await getApplicationDocumentsDirectory();
    Directory tempDirectory = Directory(directory.path + '\\output');
    if (!tempDirectory.existsSync()) {
      tempDirectory.createSync();
    }
    final fileName = path.basename(src);
    final newName = path.join(tempDirectory.path, fileName);
    logger.i('newName:$newName');
    // lumaImage(src: src, dist: newName);
    int endTime = DateTime.now().millisecondsSinceEpoch;

    time2.value = endTime - startTime;
    rustOutputPath.value = newName;
  }

  delete({int type = 0}) {
    if (type == 0) {
      imagePath.value = '';
    } else {
      rustImagePath.value = '';
    }
  }
}
